package org.meproj.cloudscale.cloud;

import org.meproj.cloudscale.algos.DetectBurstPattern;
import org.meproj.cloudscale.algos.UnderEstimationCorrection;
import org.meproj.cloudscale.database.DbUtil;
import org.meproj.cloudscale.utils.Constants;

public class CloudController {

	private String userId;
    private int predictedCountOfVMs = 0;
	public CloudController(String userId) {
		super();
		this.userId = userId;
	}
	
	public void accomodateResourceIncrease(Constants resourceType, float violationDegree) {
		DbUtil dbUtil = new DbUtil();
		int increaseVMs = 0;
		
		if((increaseVMs = dbUtil.getCurrentIncreaseInVMs(userId)) < 1) {
		
			DetectBurstPattern burstPattern = new DetectBurstPattern();
			predictedCountOfVMs = burstPattern.predictBurstBasedOnHistory(violationDegree);
		    increaseVMs = dbUtil.setCurrentIncreaseInVMs(userId, predictedCountOfVMs);
			
		} else {
		
			int totalCurrentVMs = dbUtil.getCurrentTotalVMs(userId);
			int nextPredictedCountOfVMs = totalCurrentVMs + increaseVMs;
			
			UnderEstimationCorrection estimationCorrection = null;
			
			if(resourceType == Constants.violationDegreeForCPU) {
			
				estimationCorrection = new UnderEstimationCorrection(totalCurrentVMs, nextPredictedCountOfVMs, 
								Constants.cpuAlphaMin.getFloatValue(), Constants.cpuAlphaMax.getFloatValue());
			
			} else if(resourceType == Constants.violationDegreeForMemory) {
				
				estimationCorrection = new UnderEstimationCorrection(totalCurrentVMs, nextPredictedCountOfVMs, 
								Constants.memoryAlphaMin.getFloatValue(), Constants.memoryAlphaMax.getFloatValue());
			}
			
			predictedCountOfVMs = nextPredictedCountOfVMs + Math.round(estimationCorrection.calculateAlpha());
			
		}
	}
}
